from __future__ import absolute_import
import os
from subprocess import check_call
from forest.registry import register_tool
from forest.tool import Tool
import logging

logger = logging.getLogger('tools.system.copytree')
@register_tool('system.copytree')
def copytree(src, dest, preserve=True):
    '''Copy a tree of files using cp -a, thus preserving modes, timestamps,
    links, acls, sparse files, xattrs, selinux contexts, etc.
    If preserve is False, uses cp -R (useful for modeless filesystems)'''
    chdir = lambda: os.chdir(src)
    cp = ["cp", "-a"] if preserve else ["cp", "-R", "-L"]
    #print (cp + [src, os.path.abspath(dest)])
    
    dest = os.path.abspath(dest)
    
    logger.info("Copytree %s -> %s", src, dest)
    
    check_call(cp + [src, dest], preexec_fn=chdir)
